import type { TemplateInfo } from '../types/index.js';

export class TemplateEngine {
  private templates: Map<string, TemplateInfo> = new Map();

  constructor() {
    this.initializeTemplates();
  }

  private initializeTemplates(): void {
    // 登录页面模板
    this.registerTemplate({
      name: 'login-form',
      category: 'auth',
      description: '登录表单页面模板',
      framework: 'react',
      template: `import React from 'react';
import { Form, Input, Button, Card, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';

const LoginForm: React.FC = () => {
  const [form] = Form.useForm();

  const onFinish = (values: any) => {
    console.log('登录信息:', values);
    message.success('登录成功！');
  };

  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '100vh' }}>
      <Card title="用户登录" style={{ width: 400 }}>
        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default LoginForm;`,
      dependencies: ['antd', 'react'],
      props: []
    });

    // 数据表格模板
    this.registerTemplate({
      name: 'data-table',
      category: 'data',
      description: '数据表格页面模板',
      framework: 'react',
      template: `import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Input, Card, message } from 'antd';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
}

const DataTable: React.FC = () => {
  const [data, setData] = useState<DataType[]>([]);
  const [loading, setLoading] = useState(false);

  const columns: ColumnsType<DataType> = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: '住址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="link">编辑</Button>
          <Button type="link" danger>删除</Button>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      setData([
        {
          key: '1',
          name: '胡彦斌',
          age: 32,
          address: '西湖区湖底公园1号',
        },
        {
          key: '2',
          name: '胡彦祖',
          age: 42,
          address: '西湖区湖底公园1号',
        },
      ]);
      setLoading(false);
    }, 1000);
  };

  return (
    <Card title="数据管理">
      <div style={{ marginBottom: 16 }}>
        <Space>
          <Button type="primary" icon={<PlusOutlined />}>
            新增
          </Button>
          <Input
            placeholder="搜索..."
            prefix={<SearchOutlined />}
            style={{ width: 200 }}
          />
        </Space>
      </div>
      <Table
        columns={columns}
        dataSource={data}
        loading={loading}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => \`共 \${total} 条记录\`,
        }}
      />
    </Card>
  );
};

export default DataTable;`,
      dependencies: ['antd', 'react'],
      props: []
    });

    // 仪表板模板
    this.registerTemplate({
      name: 'dashboard',
      category: 'layout',
      description: '仪表板页面模板',
      framework: 'react',
      template: `import React from 'react';
import { Card, Row, Col, Statistic, Progress, List } from 'antd';
import { ArrowUpOutlined, ArrowDownOutlined, UserOutlined, ShoppingCartOutlined } from '@ant-design/icons';

const Dashboard: React.FC = () => {
  const data = [
    { title: '用户注册', count: 1234, growth: 12.5, icon: <UserOutlined /> },
    { title: '订单数量', count: 5678, growth: -3.2, icon: <ShoppingCartOutlined /> },
  ];

  const listData = [
    '用户张三刚刚注册',
    '订单#001已完成',
    '系统维护通知',
    '新功能上线',
  ];

  return (
    <div>
      <Row gutter={16} style={{ marginBottom: 24 }}>
        {data.map((item, index) => (
          <Col span={12} key={index}>
            <Card>
              <Statistic
                title={item.title}
                value={item.count}
                precision={0}
                valueStyle={{ color: item.growth > 0 ? '#3f8600' : '#cf1322' }}
                prefix={item.icon}
                suffix={
                  item.growth > 0 ? (
                    <ArrowUpOutlined />
                  ) : (
                    <ArrowDownOutlined />
                  )
                }
              />
              <div style={{ marginTop: 8 }}>
                增长率: {item.growth > 0 ? '+' : ''}{item.growth}%
              </div>
            </Card>
          </Col>
        ))}
      </Row>

      <Row gutter={16}>
        <Col span={12}>
          <Card title="项目进度">
            <Progress percent={75} status="active" />
            <Progress percent={60} type="circle" />
          </Card>
        </Col>
        <Col span={12}>
          <Card title="最新动态">
            <List
              dataSource={listData}
              renderItem={(item) => (
                <List.Item>{item}</List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard;`,
      dependencies: ['antd', 'react'],
      props: []
    });

    // UmiJS 登录页面模板
    this.registerTemplate({
      name: 'umi-login-form',
      category: 'auth',
      description: 'UmiJS 登录表单页面模板',
      framework: 'umi',
      template: `import React from 'react';
import { Form, Input, Button, Card, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { history } from 'umi';
import styles from './index.less';

const LoginPage: React.FC = () => {
  const [form] = Form.useForm();

  const onFinish = (values: any) => {
    console.log('登录信息:', values);
    message.success('登录成功！');
    // UmiJS 路由跳转
    history.push('/dashboard');
  };

  return (
    <div className={styles.container}>
      <Card title="用户登录" className={styles.loginCard}>
        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default LoginPage;`,
      dependencies: ['antd', 'react', 'umi'],
      props: []
    });

    // Umi Max 登录页面模板
    this.registerTemplate({
      name: 'umi-max-login-form',
      category: 'auth',
      description: 'Umi Max 登录表单页面模板',
      framework: 'umi-max',
      template: `import React from 'react';
import { Form, Input, Button, Card, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { history, useModel, useRequest } from '@umijs/max';
import styles from './index.less';

interface LoginParams {
  username: string;
  password: string;
}

const LoginPage: React.FC = () => {
  const [form] = Form.useForm();
  const { setInitialState } = useModel('@@initialState');

  // 使用 useRequest 处理登录请求
  const { run: login, loading } = useRequest(
    async (params: LoginParams) => {
      const response = await fetch('/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(params),
      });
      return response.json();
    },
    {
      manual: true,
      onSuccess: (result) => {
        if (result.success) {
          message.success('登录成功！');
          setInitialState({
            name: result.data.name,
            avatar: result.data.avatar,
          });
          history.push('/dashboard');
        } else {
          message.error(result.message || '登录失败');
        }
      },
    },
  );

  const onFinish = (values: LoginParams) => {
    login(values);
  };

  return (
    <div className={styles.container}>
      <Card title="用户登录" className={styles.loginCard}>
        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default LoginPage;`,
      dependencies: ['antd', 'react', '@umijs/max'],
      props: []
    });
  }

  registerTemplate(template: TemplateInfo): void {
    this.templates.set(template.name, template);
  }

  getTemplate(name: string): TemplateInfo | undefined {
    return this.templates.get(name);
  }

  getAllTemplates(): TemplateInfo[] {
    return Array.from(this.templates.values());
  }

  getTemplatesByCategory(category?: string, framework?: string): TemplateInfo[] {
    let templates = Array.from(this.templates.values());
    
    if (category) {
      templates = templates.filter(t => t.category === category);
    }
    
    if (framework) {
      templates = templates.filter(t => t.framework === framework);
    }
    
    return templates;
  }

  renderTemplate(templateName: string, context: Record<string, any>): string {
    const template = this.getTemplate(templateName);
    
    if (!template) {
      throw new Error(`Template not found: ${templateName}`);
    }

    let rendered = template.template;
    
    // 简单的模板变量替换
    for (const [key, value] of Object.entries(context)) {
      const regex = new RegExp(`{{\\s*${key}\\s*}}`, 'g');
      rendered = rendered.replace(regex, String(value));
    }

    return rendered;
  }
}